package cn.samler.shopapi.Service.impl;

import cn.samler.shopapi.Config.TencentCloudConfig;
import cn.samler.shopapi.Model.Sys.ServiceResult;
import cn.samler.shopapi.Service.UploadService;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Service;

import java.io.InputStream;

@Service
public class UploadServiceImpl implements UploadService {
    private final TencentCloudConfig tencentCloudConfig;

    UploadServiceImpl(TencentCloudConfig tencentCloudConfig) {
        this.tencentCloudConfig = tencentCloudConfig;
    }

    @Override
    public ServiceResult upload(InputStream inputStream, String filename) {
        COSCredentials cred = new BasicCOSCredentials(this.tencentCloudConfig.getSecretId(), this.tencentCloudConfig.getSecretKey());
        Region region = new Region(this.tencentCloudConfig.getCos().getRegion());
        COSClient client = new COSClient(cred, new ClientConfig(region));

        // 开始上传
        try {
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(inputStream.available());

            PutObjectRequest objectRequest = new PutObjectRequest(this.tencentCloudConfig.getCos().getBucketName(), filename, inputStream, metadata);
            client.putObject(objectRequest);

            return ServiceResult.success(this.tencentCloudConfig.getCos().getDomain() + filename);
        } catch (Exception e) {
            return ServiceResult.failure(e);
        } finally {
            client.shutdown();
        }
    }
}
